// src/stores/iam/IamUserStore.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'
import request from '@/utils/request'
import type { User, UserCreation, UserUpdate } from '@/types/iam/IamUser'

// 模拟数据
const mockUsers: User[] = [
  {
    user_id: 1,
    user_code: 'ADMIN001',
    user_name: '管理员',
    hr_employee_code: 'EMP001',
    password_hash: 'hashed_password_1',
    email: 'admin@example.com',
    is_active: true,
    last_login: '2023-11-20T10:30:00Z',
    hr_employee_id: 101,
    created_at: '2023-01-15T08:00:00Z',
    updated_at: '2023-10-10T14:20:00Z',
    created_by: 'system',
    updated_by: 'system',
    is_deleted: false
  },
  {
    user_id: 2,
    user_code: 'USER001',
    user_name: '张三',
    hr_employee_code: 'EMP002',
    password_hash: 'hashed_password_2',
    email: 'zhangsan@example.com',
    is_active: true,
    last_login: '2023-11-19T16:45:00Z',
    hr_employee_id: 102,
    created_at: '2023-02-20T09:15:00Z',
    updated_at: '2023-11-05T11:30:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    user_id: 3,
    user_code: 'USER002',
    user_name: '李四',
    hr_employee_code: 'EMP003',
    password_hash: 'hashed_password_3',
    email: 'lisi@example.com',
    is_active: false,
    last_login: '2023-11-10T09:20:00Z',
    hr_employee_id: 103,
    created_at: '2023-03-05T10:40:00Z',
    updated_at: '2023-11-15T15:10:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    user_id: 4,
    user_code: 'USER003',
    user_name: '王五',
    hr_employee_code: 'EMP004',
    password_hash: 'hashed_password_4',
    email: 'wangwu@example.com',
    is_active: true,
    last_login: '2023-11-20T08:15:00Z',
    hr_employee_id: 104,
    created_at: '2023-04-10T13:25:00Z',
    updated_at: '2023-11-18T10:50:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  },
  {
    user_id: 5,
    user_code: 'USER004',
    user_name: '赵六',
    hr_employee_code: 'EMP005',
    password_hash: 'hashed_password_5',
    email: 'zhaoliu@example.com',
    is_active: true,
    last_login: '2023-11-19T14:30:00Z',
    hr_employee_id: 105,
    created_at: '2023-05-15T11:10:00Z',
    updated_at: '2023-11-16T16:20:00Z',
    created_by: 'admin',
    updated_by: 'admin',
    is_deleted: false
  }
]

export const useIamUserStore = defineStore('iamUser', () => {
  // 初始化时使用模拟数据
  const userList = ref<User[]>(mockUsers)
  const currentUser = ref<User | null>(null)
  // 导出mockUsers以便在组件中直接访问
  const mockUsersRef = ref<User[]>(mockUsers)

  const isEditing = ref(false)

  // 获取用户列表
  const fetchUserList = async (signal?: AbortSignal) => {
    try {
      const response = await request.get('/iam/users', { signal })

      // 调整返回数据处理方式
      if (response && Array.isArray(response.data)) {
        userList.value = response.data
      } else {
        // 如果不是数组类型，使用模拟数据并打印警告
        console.warn('获取的用户列表数据类型不正确，期望数组但得到:', typeof response.data)
        // 检查是否是HTML字符串
        if (response && typeof response.data === 'string' && (response.data as string).includes('<!DOCTYPE html>')) {
          console.error('API返回了HTML文档而不是JSON数据，这可能是因为后端接口未正确配置或存在CORS问题')
        }
        // 使用模拟数据代替
        userList.value = [...mockUsers]
      }
    } catch (error) {
      // 如果接口调用失败，继续使用模拟数据
      if ((error as Error).name !== 'AbortError') {
        console.warn('获取用户列表失败，使用模拟数据:', error)
        // 使用模拟数据
        userList.value = [...mockUsers]
      }
    }
  }

  // 新增用户
  const addUser = async (user: UserCreation, signal?: AbortSignal) => {
    try {
      const response = await request.post('/api/iam/users', {
        ...user,
        password: user.password_hash,
        password_hash: undefined
      }, { signal })

      // 调整返回数据处理方式
      if (response && response.data) {
        userList.value.push(response.data)
      }
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('新增用户失败:', error)
        // 模拟添加成功
        const newUser: User = {
          ...user as User,
          user_id: Date.now(), // 使用时间戳作为临时ID
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
          is_deleted: false
        }
        userList.value.push(newUser)
        console.log('已添加模拟用户')
      }
    }
  }

  // 编辑用户
  const updateUser = async (id: number, user: UserUpdate, signal?: AbortSignal) => {
    try {
      const response = await request.put(`/api/iam/users/${id}`, user, { signal })

      // 调整返回数据处理方式
      if (response && response.data) {
        const index = userList.value.findIndex((u) => u.user_id === id)
        if (index !== -1) {
          userList.value[index] = { ...userList.value[index], ...response.data }
        }
      }
    } catch (error) {
      if ((error as Error).name !== 'AbortError') {
        console.error('编辑用户失败:', error)
        // 模拟编辑成功
        const index = userList.value.findIndex((u) => u.user_id === id)
        if (index !== -1) {
          userList.value[index] = {
            ...userList.value[index],
            ...user,
            updated_at: new Date().toISOString()
          }
        }
        console.log('已更新模拟用户')
      }
    }
  }

  // 删除用户
  const deleteUser = async (id: number, signal?: AbortSignal) => {
    try {
      await request.delete(`/api/iam/users/${id}`, { signal })
      userList.value = userList.value.filter((u) => u.user_id !== id)
    } catch (error) {
      // 使用类型断言将 error 转换为 Error 类型
      if ((error as Error).name !== 'AbortError') {
        console.error('删除用户失败:', error)
        // 模拟删除成功
        userList.value = userList.value.filter((u) => u.user_id !== id)
        console.log('已删除模拟用户')
      }
    }
  }

  // 设置当前编辑用户
  const setCurrentUser = (user: User | null) => {
    currentUser.value = user
    isEditing.value = !!user
  }

  return {
    userList,
    currentUser,
    mockUsers: mockUsersRef,
    isEditing,
    fetchUserList,
    addUser,
    updateUser,
    deleteUser,
    setCurrentUser,
  }
})